package com.shijie.sjoj.model.typehandler;

import com.shijie.sjoj.model.base.BaseValueEnumSerialize;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 实现BaseEnumSerialize接口枚举类jdbc类型处理类
 *
 * @author ZSJ
 */
@Slf4j
@MappedTypes(BaseValueEnumSerialize.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class BaseValueEnumSerializeTypeHandler extends BaseTypeHandler<BaseValueEnumSerialize<? extends BaseValueEnumSerialize<?>>> {

    @Override
    public void setParameter(PreparedStatement ps, int i, BaseValueEnumSerialize<? extends BaseValueEnumSerialize<?>> parameter, JdbcType jdbcType) throws SQLException {
        // 注册新的枚举实例
        BaseValueEnumSerialize.InheritDefInstanceRegister.register(parameter);
        // （父级）sql处理
        super.setParameter(ps, i, parameter, jdbcType);
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, BaseValueEnumSerialize<? extends BaseValueEnumSerialize<?>> parameter, JdbcType jdbcType) throws SQLException {
        // 注册新的枚举实例
        BaseValueEnumSerialize.InheritDefInstanceRegister.register(parameter);
        // sql处理，填充值
        ps.setString(i, parameter.getValue());
    }

    @Override
    public BaseValueEnumSerialize<? extends BaseValueEnumSerialize<?>> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        // 从数据库结果集获取值
        String value = rs.getString(columnName);
        // 进行枚举转换
        return BaseValueEnumSerialize.of(value);
    }

    @Override
    public BaseValueEnumSerialize<? extends BaseValueEnumSerialize<?>> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        // 从数据库结果集获取值
        String value = rs.getString(columnIndex);
        // 进行枚举转换
        return BaseValueEnumSerialize.of(value);
    }

    @Override
    public BaseValueEnumSerialize<? extends BaseValueEnumSerialize<?>> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        // 从数据库结果集获取值
        String value = cs.getString(columnIndex);
        // 进行枚举转换
        return BaseValueEnumSerialize.of(value);
    }


}
